package com.wpp.util;

import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Classname SpringContentHolder
 * @Description
 * @Date 2020/12/11 22:39
 * @Created by wpp25
 */
public class SpringContentHolder implements ApplicationContextAware, DisposableBean {

    public static  ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    @Override
    public void destroy() throws Exception {
        clear();
    }
    public static void clear () {
        applicationContext = null;
    }


    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return (T) applicationContext.getBean(requiredType);
    }

    private static void assertContextInjected() {
        Objects.requireNonNull(applicationContext,"applicationContext 未注入");
    }

}
